﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.common.http;

namespace com.lover.astd.common.partner.impl
{
    public class IspeakLogin : LoginImplBase
    {
        public IspeakLogin() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            string loginurl = "http://www.iugame.cn/common/Login.ashx";
            string data = String.Format("uid={0}&pwd={1}", _username, _md5_password_lower);
            HttpResult resp = TransferMgr.doPostPure(loginurl, data, ref cookies, "http://www.iugame.cn/astd/fwq.aspx");
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            string retstr = resp.getContent();

            if (retstr.IndexOf("alert") >= 0)
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }

            // must get uscode cookie
            if (resp.getCookies().Count == 0) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }
            string uscode = "";
            foreach (Cookie cookie in resp.getCookies())
            {
                if (cookie == null) continue;
                if (cookie.Name == "uscode")
                {
                    uscode = cookie.Value;
                    break;
                }
            }
            if (uscode == "") { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            string play_url = String.Format("http://gameroom1.iugame.cn/play.ashx?iusiteid=1&s={0}&gname=2&sname=270", uscode);
            resp = TransferMgr.doGetPure(play_url, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }
            string location = resp.getExtraHeader("Location");
            if (location == null) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }

            if(!location.StartsWith("http")) location = "http://gameroom1.iugame.cn" + location;
            resp = TransferMgr.doGetPure(location, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }
            location = resp.getExtraHeader("Location");
            if (location == null) { result.StatusCode = LoginStatusCode.FailInGetSession; return result; }

            processRedirect(location, result, ref cookies);
            return result;
        }
    }
}
